<template>
<!-- 医疗机构管理 -->
  <div class="medical-institution-container">
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :model="searchForm" class="search-form" label-width="80px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="机构名称">
              <el-input
                v-model="searchForm.institutionName"
                placeholder="请输入医疗机构名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="机构编码">
              <el-input
                v-model="searchForm.institutionCode"
                placeholder="请输入机构编码"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="机构等级">
              <el-select
                v-model="searchForm.institutionLevel"
                placeholder="请选择机构等级"
                clearable
              >
                <el-option label="一级" :value="1" />
                <el-option label="二级" :value="2" />
                <el-option label="三级" :value="3" />
                <el-option label="四级" :value="4" />
                <el-option label="五级" :value="5" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="6" class="search-buttons">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i> 新增医疗机构
      </el-button>
    </div>

    <!-- 表格 -->
    <div>
      <el-table
        :data="tableData"
        border
        style="width: 100%;display:flex;"
        v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="institutionId" label="机构ID" width="100" align="center" />
        <el-table-column prop="institutionName" label="机构名称" width="180" show-overflow-tooltip />
        <el-table-column prop="institutionCode" label="机构编码" width="150" align="center" />
        <el-table-column prop="regionCode" label="区域编码" width="150" align="center" />
        <el-table-column label="机构等级" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.institutionLevel)">
              {{ getLevelText(row.institutionLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="mini" type="primary" plain @click="handleEdit(row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="机构名称" prop="institutionName">
          <el-input v-model="formData.institutionName" placeholder="请输入医疗机构名称" />
        </el-form-item>
        <el-form-item label="机构编码" prop="institutionCode">
          <el-input v-model="formData.institutionCode" placeholder="请输入机构编码" />
        </el-form-item>
        <el-form-item label="区域编码" prop="regionCode">
          <el-input v-model="formData.regionCode" placeholder="请输入行政区域编码" />
        </el-form-item>
        <el-form-item label="机构等级" prop="institutionLevel">
          <el-select v-model="formData.institutionLevel" placeholder="请选择机构等级">
            <el-option label="一级" :value="1" />
            <el-option label="二级" :value="2" />
            <el-option label="三级" :value="3" />
            <el-option label="四级" :value="4" />
            <el-option label="五级" :value="5" />
          </el-select>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { ElMessage } from 'element-plus';

export default {
  name: 'MedicalInstitution',
  data() {
    return {
      // 搜索参数
      searchForm: {
        institutionName: '',
        institutionCode: '',
        institutionLevel: null
      },

      // 表格数据
      tableData: [],
      loading: false,

      // 分页参数
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },

      // 对话框状态
      dialogVisible: false,
      dialogTitle: '新增医疗机构',
      formData: {
        institutionId: null,
        institutionName: '',
        institutionCode: '',
        regionCode: '',
        institutionLevel: null
      },

      // 表单验证规则
      formRules: {
        institutionName: [
          { required: true, message: '请输入医疗机构名称', trigger: 'blur' },
          { min: 2, max: 100, message: '机构名称长度2 - 100位', trigger: 'blur' }
        ],
        institutionCode: [
          { required: true, message: '请输入机构编码', trigger: 'blur' },
          { min: 6, max: 20, message: '机构编码长度6 - 20位', trigger: 'blur' }
        ],
        regionCode: [
          { required: true, message: '请输入行政区域编码', trigger: 'blur' },
          { min: 6, max: 12, message: '区域编码长度6 - 12位', trigger: 'blur' }
        ],
        institutionLevel: [
          { required: true, message: '请选择机构等级', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 获取医疗机构列表
    fetchData() {
      this.loading = true
      request.get('/medicalInstitution/list', {
        params: {
          current: this.pagination.currentPage,
          size: this.pagination.pageSize,
          institutionName: this.searchForm.institutionName,
          institutionCode: this.searchForm.institutionCode,
          institutionLevel: this.searchForm.institutionLevel
        }
      })
      .then(res => {
        if (res.code === 200) {
          this.tableData = res.data.records
          this.pagination.total = res.data.total
        } else {
          this.$message.error(res.message || '获取数据失败')
        }
      })
      .catch(err => {
        console.error('获取医疗机构列表失败:', err)
        this.$message.error('加载医疗机构列表失败')
      })
      .finally(() => {
        this.loading = false
      })
    },

    // 搜索医疗机构
    handleSearch() {
      this.pagination.currentPage = 1
      this.fetchData()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        institutionName: '',
        institutionCode: '',
        institutionLevel: null
      }
      this.handleSearch()
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchData()
    },

    // 新增医疗机构
    handleAdd() {
      this.dialogTitle = '新增医疗机构'
      this.resetForm()
      this.dialogVisible = true
    },

    // 编辑医疗机构
    handleEdit(row) {
      this.dialogTitle = '编辑医疗机构'
      this.formData = {
        institutionId: row.institutionId,
        institutionName: row.institutionName,
        institutionCode: row.institutionCode,
        regionCode: row.regionCode,
        institutionLevel: row.institutionLevel
      }
      this.dialogVisible = true
    },

    // 删除单个医疗机构
    handleDelete(row) {
      this.$confirm(`确认删除医疗机构 "${row.institutionName}" 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        request.post(`/medicalInstitution/delete/${row.institutionId}`)
          .then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功')
              this.fetchData()
            } else {
              this.$message.error(res.message || '删除失败')
            }
          })
          .catch(err => {
            this.$message.error('删除失败')
          })
      }).catch(() => {})
    },

    // 提交表单
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return

        const isEdit = !!this.formData.institutionId
        const apiUrl = isEdit ? '/medicalInstitution/update' : '/medicalInstitution/create'
        const method = 'post'

        request[method](apiUrl, this.formData)
          .then(res => {
            if (res.code === 200) {
              this.$message.success(`${this.dialogTitle}成功`)
              this.dialogVisible = false
              this.fetchData()
            } else {
              this.$message.error(res.message || `${this.dialogTitle}失败`)
            }
          })
          .catch(err => {
            this.$message.error(`${this.dialogTitle}失败`)
          })
      })
    },

    // 重置表单
    resetForm() {
      this.$refs.formRef && this.$refs.formRef.resetFields()
      this.formData = {
        institutionId: null,
        institutionName: '',
        institutionCode: '',
        regionCode: '',
        institutionLevel: null
      }
    },
    
    // 获取机构等级文本
    getLevelText(level) {
      const levels = {
        1: '一级',
        2: '二级',
        3: '三级',
        4: '四级',
        5: '五级'
      }
      return levels[level] || '未知'
    },
    
    // 获取等级标签类型
    getLevelTagType(level) {
      const types = {
        1: 'danger',
        2: 'warning',
        3: 'primary',
        4: 'success',
        5: 'info'
      }
      return types[level] || ''
    }
  }
}
</script>

<style scoped>
.medical-institution-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 100%;
}

.operation-buttons {
  display:flex;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 表格样式优化 */
.el-table {
  font-size: 14px;
}

.el-table th {
  font-weight: bold;
  color: #333;
}

.el-table .cell {
  padding: 8px 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-buttons {
    justify-content: flex-start;
    margin-top: 10px;
  }
  
  .el-col {
    margin-bottom: 10px;
  }
}
</style>